#!/usr/bin/env python3
import select
import os
import sys

Timeout = 300.0  # timeout after 5min


def meson(line: str) -> None:
    if len(line) == 0:
        raise EOFError  # EOF
    if line.startswith("Installing"):
        # handle with meson install
        args = line.strip().split(' ')
        print("Generate", os.path.join(
            './',
            os.path.relpath(args[3], os.getcwd()),
            args[1]
        ))
    elif line.startswith("Skipping RPATH fixing"):
        pass  # filter out
    else:
        print(line, end="")


def main(str: str) -> None:
    args = str.strip().split(' ')
    if len(args) >= 2:
        # normal relpath
        print(os.path.relpath(*str.split(' ')[0:1]))
    else:
        print('Usage ./relpath.py <path> <start>')


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == '--meson-install':
        while True:
            try:
                if not select.select([sys.stdin, ], [], [], Timeout)[0]:
                    raise TimeoutError("Timeout %.3fs" % Timeout)
                meson(sys.stdin.readline())
            except (EOFError, StopIteration):
                break  # eof
            except KeyboardInterrupt:
                break  # don't print traceback
            except TimeoutError as err:
                print(err, file=sys.stderr)
                break  # don't print timeout notice
            except Exception as err:
                print(type(err), err)
            pass
    else:
        main(sys.stdin.read())
